package com.spi.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.savedrequest.NullRequestCache;

@Configuration
@EnableWebSecurity
public class AuthenticationConfig {

    private void commonHttpSetting(HttpSecurity httpSecurity) throws Exception {
        //禁用不必要的filter 禁用远古时期产物 前后端分离用不到的过滤器
        httpSecurity.formLogin(AbstractHttpConfigurer::disable)
                .httpBasic(AbstractHttpConfigurer::disable)
                .logout(AbstractHttpConfigurer::disable)
                .sessionManagement(AbstractHttpConfigurer::disable)
                .csrf(AbstractHttpConfigurer::disable)
                .requestCache(cache -> cache.requestCache(new NullRequestCache()))
                .anonymous(AbstractHttpConfigurer::disable);
    }
    @Bean
    public SecurityFilterChain publicApiFilterChain(HttpSecurity httpSecurity) throws Exception {
        commonHttpSetting(httpSecurity);
        //默认认证所有请求
        httpSecurity.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated());

        //自定义过滤器链 插入到springsecurity权限认证模块中，添加在UsernamePasswordAuthenticationFilter之前
        httpSecurity.addFilterBefore(new MyCustomerFilter(), UsernamePasswordAuthenticationFilter.class);
        return httpSecurity.build();
    }
}
